<template>
    <div class="wrap">
        <div style="display: flex; align-items: center; justify-content: space-between; height: 30px;">
            <div class="title">客户档案</div>
            <el-icon :size="25" @click="closeSidebar" style="cursor: pointer;">
                <Close />
            </el-icon>
        </div>
        <div v-if="!isEdit">
            <div class="content">
                <div class="tit">基本信息</div>
                <el-form label-width="120px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="客户类型：">
                                <div v-if="infoShow.auth_type == 1">企业</div>
                                <div v-else>个人</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="用户名称：">
                                <div>{{ infoShow.auth_name }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item :label="infoShow.auth_type == 1 ? '营业执照：' : '身份证：'">
                                <div v-if="infoShow.license">
                                    <el-image style="width: 120px; height: 80px; border-radius: 6px;"
                                        :src="infoShow.license" :preview-src-list="[infoShow.license]" fit="cover" />
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="二级类型：">
                                {{ infoShow.enterprise_type }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="联系电话：">
                                <div>{{ infoShow.mobile }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="联系地址：">
                                <div>{{ infoShow.contact_address }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="性别：">
                                <div>{{ infoShow.sex == 0 ? '男' : '女' }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="民族：" prop="nation">
                                <div>{{ infoShow.nation }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="出生日期：">
                                <div>{{ infoShow.birthday }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="行业类型：">
                                <template v-for="(item, index) in industryList">
                                    <span v-if="item.id == archiveInfo.industry_id" :key="index">{{ item.name }}</span>
                                </template>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="infoShow.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="主营行业：">
                                <div>{{ infoShow.main_business }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="购买动机：" prop="pm">
                                <div>{{ infoShow.pm }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="tit" v-if="infoShow.auth_type == 1">法定代表人信息</div>
                    <el-row v-if="infoShow.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="姓名：" prop="legal_person">
                                <div>{{ infoShow.legal_person }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <el-button @click="handleEdit">编辑客户档案</el-button>
                <el-button type="primary" @click="handleSendInfo">发送至群聊</el-button>
            </div>
        </div>
        <div v-else>
            <div class="content">
                <div class="tit">基本信息</div>
                <el-form label-width="120px" :model="archiveInfo" ref="ruleFormRef" :rules="rules">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="客户类型：" prop="auth_type">
                                <el-select v-model="archiveInfo.auth_type" placeholder="请选择" style="width: 240px;">
                                    <el-option v-for="item in type" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="用户名称：" prop="auth_name">
                                <el-input v-model="archiveInfo.auth_name" style="width: 240px" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item :label="archiveInfo.auth_type == 1 ? '营业执照：' : '身份证：'" prop="license">
                                <el-upload
                                    style="width: 120px; height: 80px; border-radius: 6px; border: dashed 1px #ccc; display: flex; align-items: center; justify-content: center; cursor: pointer;"
                                    :action="uploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload">
                                    <img v-if="archiveInfo.license" :src="archiveInfo.license"
                                        style="width: 120px; height: 80px; border-radius: 6px;" />
                                    <el-icon v-else class="avatar-uploader-icon" size="30" color="#cccccc">
                                        <Postcard />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="二级类型：" prop="enterprise_type">
                                <el-select v-model="archiveInfo.enterprise_type" placeholder="请选择"
                                    style="width: 240px;">
                                    <el-option v-for="item in companyType" :key="item" :label="item" :value="item" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="联系电话：" prop="mobile">
                                <el-input v-model="archiveInfo.mobile" style="width: 240px" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="性别：" prop="sex">
                                <el-select v-model="archiveInfo.sex" placeholder="请选择" style="width: 240px;">
                                    <el-option v-for="item in sex" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="民族：" prop="nation">
                                <el-input v-model="archiveInfo.nation" style="width: 240px" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 2">
                        <el-col :span="24">
                            <el-form-item label="出生日期：" prop="birthday">
                                <el-date-picker v-model="archiveInfo.birthday" type="date" placeholder="请选择"
                                    :default-value="archiveInfo.birthday ? new Date(archiveInfo.birthday.replace(/-/g, ',')) : new Date(1996, 9, 1)"
                                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="行业类型：" prop="industry_id">
                                <el-select v-model="archiveInfo.industry_id" placeholder="请选择" style="width: 240px;">
                                    <el-option v-for="item in industryList" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="archiveInfo.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="主营行业：" prop="main_business">
                                <el-input v-model="archiveInfo.main_business" style="width: 240px"
                                    :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="联系地址：" prop="contact_address">
                                <el-input v-model="archiveInfo.contact_address" style="width: 240px"
                                    placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="购买动机：" prop="pm">
                                <el-select v-model="archiveInfo.pm" placeholder="请选择" style="width: 240px;">
                                    <el-option v-for="item in pmList" :key="item" :label="item" :value="item" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="tit" v-if="archiveInfo.auth_type == 1">法定代表人信息</div>
                    <el-row v-if="archiveInfo.auth_type == 1">
                        <el-col :span="24">
                            <el-form-item label="姓名：" prop="legal_person">
                                <el-input v-model="archiveInfo.legal_person" style="width: 240px" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="tit">修改信息</div>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="发现方式：" prop="find">
                                <el-select v-model="archiveInfo.find" placeholder="请选择" style="width: 240px;">
                                    <el-option v-for="item in findList" :key="item" :label="item" :value="item" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="修改原因：" prop="remark">
                                <el-input v-model="archiveInfo.remark" style="width: 240px"
                                    :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="聊天记录：" prop="chat_log">
                                <el-button type="primary" :disabled="mulitpleSelectStore.isOpen"
                                    @click="handleSelectMsg">点击添加</el-button>
                                <div style="font-size: 12px; margin-left: 10px; padding: 0 10px; background-color: #eee; border-radius: 5px; cursor: pointer;"
                                    @click="openSelectMsg" v-if="mulitpleSelectStore.selectList.length > 0">
                                    当前选中<span style="color: #f00;">{{ mulitpleSelectStore.selectList.length
                                        }}条</span>聊天记录
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="其他文件：" prop="file">
                                <el-upload class="upload-demo" drag :action="uploadUrl" multiple
                                    :on-success="handleFileSuccess" style="display: flex;">
                                    <el-icon class="el-icon--upload" size="40"><upload-filled /></el-icon>
                                    <div style="font-size: 12px; line-height: 20px; color: #666;">
                                        点击或拖拽文件上传</br>文件不超过20M</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <el-button @click="isEdit = false">取消</el-button>
                <el-button type="primary" @click="handleEditInfo(ruleFormRef)">保存</el-button>
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="发送至群聊" width="500">
        <div style="font-size: 14px; color: #666; margin-bottom: 10px;">选择发送信息：</div>
        <el-select v-model="sendInfo" multiple placeholder="请选择">
            <el-option v-for="item in sendInfoOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sendMessage">
                    确认发送
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="showMsgList" title="选中的聊天记录" width="700">
        <div style="height: calc(100vh - 300px); overflow-y: scroll;">
            <el-timeline style="max-width: 650px">
                <el-timeline-item :timestamp="formatTimestamp(item.clientTime)" placement="top"
                    v-for="(item, index) in mulitpleSelectStore.selectList" :key="index">
                    <el-card>
                        <h4
                            style="margin-bottom: 10px; color: #999; display: flex; align-items: center; justify-content: space-between;">
                            <span>{{ item.nick }}{{ item.from.includes('FW') ?
                                '（法务）' : (item.from == 'administrator' ? '' : '（客户）') }}</span>
                            <el-icon size="16" color="#666666" style="cursor: pointer;" @click="delMsg(index)">
                                <Delete />
                            </el-icon>
                        </h4>
                        <div v-if="item.type == 'TIMTextElem'">
                            <p>{{ item.payload.text }}</p>
                        </div>
                        <div v-if="item.type == 'TIMLocationElem'"></div>
                        <div v-if="item.type == 'TIMFaceElem'">【表情消息】</div>
                        <div v-if="item.type == 'TIMCustomElem'">
                            <div v-if="JSON.parse(item.payload.data).type == 'imgMsg'">
                                <div v-html="JSON.parse(item.payload.data).ext"></div>
                                <el-image style="width: 80px; height: 80px;"
                                    :src="JSON.parse(item.payload.data).imageUrl"
                                    :preview-src-list="[JSON.parse(item.payload.data).imageUrl]" fit="cover"
                                    v-if="JSON.parse(item.payload.data).imageUrl" />
                            </div>
                            <div v-if="JSON.parse(item.payload.data).type == 'evaluation'">【邀请评价】</div>
                            <div v-if="JSON.parse(item.payload.data).type == 'workOrder'">【工单消息】</div>
                        </div>
                        <div v-if="item.type == 'TIMSoundElem'"></div>
                        <div v-if="item.type == 'TIMImageElem'">
                            <template v-for="(itm, idx) in item.payload.imageInfoArray">
                                <el-image style="width: 80px; height: 80px;" :src="itm.imageUrl"
                                    :preview-src-list="[itm.imageUrl]" fit="cover" :key="idx" v-if="idx == 0" />
                            </template>
                        </div>
                        <div v-if="item.type == 'TIMFileElem'">
                            <a :href="item.payload.fileUrl" _blank="target">
                                <div style="display: flex; align-items: center;">
                                    <el-icon size="25" color="#666666">
                                        <FolderOpened />
                                    </el-icon>
                                    <span style="color: #409eff; margin-left: 5px;">{{ item.payload.fileName
                                        }}</span>
                                </div>
                            </a>
                        </div>
                        <div v-if="item.type == 'TIMVideoFileElem'">
                            <video width="160" height="120" controls>
                                <source :src="msg.content.VideoUrl" type="video/mp4">
                                您的浏览器不支持 video 属性。
                            </video>
                        </div>
                        <div v-if="item.type == 'TIMRelayElem'"></div>
                    </el-card>
                </el-timeline-item>
            </el-timeline>
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import TUIChatEngine, {
    TUIChatService,
    SendMessageParams,
    SendMessageOptions,
    TUIStore,
    StoreName,
    IConversationModel,
} from '@tencentcloud/chat-uikit-engine';
import { isEnabledMessageReadReceiptGlobal } from '../../TUIChat/utils/utils';
import OfflinePushInfoManager, { IOfflinePushInfoCreateParams } from '../../TUIChat/offlinePushInfoManager/index';
import { ref, watch, onMounted } from '../../../adapter-vue';
import { getArchive, editArchive, getIndustry, baseURL } from '@/api';
import { useSidebarStore } from '@/store/sidebar';
import { useMulitpleSelectStore } from '@/store/mulitpleSelect';
import type { UploadProps, FormInstance } from 'element-plus'
import { values } from 'lodash';
import { formatTimestamp } from '@/utils/format'

const sidebarStore = useSidebarStore();
const mulitpleSelectStore = useMulitpleSelectStore();
const uploadUrl = baseURL + '/admin/ajax/upload';
const currentConversation = ref<IConversationModel>();
const isEdit = ref(false);
const infoShow = ref({});
const archiveInfo = ref({});
const sex = [{
    label: '男',
    value: 0
}, {
    label: '女',
    value: 1
}]
const ruleFormRef = ref<FormInstance>();
const rules = {
    auth_type: [{ required: true, message: '请选择客户类型', trigger: 'blur' }],
    auth_name: [{ required: true, message: '请填写用户名称', trigger: 'blur' }],
    enterprise_type: [{ required: true, message: '请选择二级类型', trigger: 'blur' }],
    mobile: [{ required: true, message: '请填写联系电话', trigger: 'blur' }],
    find: [{ required: true, message: '请选择发现方式', trigger: 'blur' }],
};
const dialogVisible = ref(false);
const sendInfo = ref([]);
interface SendInfoOption {
    label: string;
    value: number;
}
const sendInfoOptions = ref<SendInfoOption[]>([]);
const type = [{
    label: '企业',
    value: 1
}, {
    label: '个人',
    value: 2
}];
const companyType = ['有限公司', '个体工商户', '个人独资企业', '普通合伙/有限合伙', '分公司/银行支行/事业单位/机关单位'];
const pmList = ['诉讼文书', '律师函', '合同服务', '法律咨询', '其他'];
const findList = ['咨询服务', '管家服务', '文本上报', '客户上报'];
interface Industry {
    id: number;
    name: string;
}
const industryList: Industry[] = [];
const showMsgList = ref(false)

onMounted(() => {
    getIndustry().then(res => {
        industryList.push(...values(res.data));
    })
})

TUIStore.watch(StoreName.CONV, {
    currentConversation: (conversation: IConversationModel) => {
        currentConversation.value = conversation;
    },
});

watch(sidebarStore, (New) => {
    if (New.isOpen) {
        if(New.type == 'archive') {
            mulitpleSelectStore.setMulitpleSelect({
                isOpen: false,
                selectList: [],
                type: 1
            })
            getArchive({
                group_id: New.groupInfo.GroupId,
                uid: New.groupInfo.bind_user_id,
            }).then(res => {
                infoShow.value = res.data;
                isEdit.value = false;
                mulitpleSelectStore.setMulitpleSelect({
                    isOpen: false,
                    selectList: res.data.chat_log ? JSON.parse(res.data.chat_log) : [],
                    type: 1
                })
            })
        }
    } else {
        mulitpleSelectStore.setMulitpleSelect({
            isOpen: false,
            selectList: [],
            type: 1
        })
    }
})

mulitpleSelectStore.$subscribe((mutate, state) => {
    if (state.selectList.length > 0) {
        archiveInfo.value.chat_log = JSON.stringify(state.selectList)
    }
})

function handleEdit() {
    getArchive({
        group_id: currentConversation?.value?.groupProfile?.groupID,
        uid: infoShow.value.uid,
    }).then(res => {
        archiveInfo.value = res.data;
        isEdit.value = true;
    })
}

function closeSidebar() {
    sidebarStore.setSidebar({
        isOpen: false,
        groupInfo: sidebarStore.groupInfo,
        type: sidebarStore.type,
        currentId: '',
    });
}

function handleSelectMsg() {
    mulitpleSelectStore.setMulitpleSelect({
        isOpen: true,
        selectList: archiveInfo.value.chat_log ? JSON.parse(archiveInfo.value.chat_log) : [],
        type: 2
    });
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
) => {
    archiveInfo.value.license = response.data.url
}

const handleFileSuccess: UploadProps['onSuccess'] = (
    response
) => {
    if (archiveInfo.value.file) {
        archiveInfo.value.file += ',' + response.data.url;
    } else {
        archiveInfo.value.file = response.data.url;
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片必须是JPG格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能大于2MB')
        return false
    }
    return true
}

function handleSendInfo() {
    type SendInfoOption = { label: string; value: number };
    let options: SendInfoOption[] = [];

    if (archiveInfo.value.auth_type == 1) {
        options = [{
            label: '用户名称',
            value: 1
        }, {
            label: '联系电话',
            value: 2
        }, {
            label: '联系地址',
            value: 3
        }, {
            label: '营业执照',
            value: 4
        }];
    } else {
        options = [{
            label: '用户名称',
            value: 1
        }, {
            label: '联系电话',
            value: 2
        }];
    }
    sendInfoOptions.value = options;
    sendInfo.value = [];
    dialogVisible.value = true;
}

const handleEditInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            archiveInfo.value.group_id = currentConversation?.value?.groupProfile?.groupID;
            editArchive(archiveInfo.value).then(res => {
                getArchive({
                    group_id: currentConversation?.value?.groupProfile?.groupID,
                    uid: infoShow.value.uid,
                }).then(res => {
                    infoShow.value = res.data;
                    isEdit.value = false;
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    });
                })

            }).catch(err => {
                console.log(err)
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const sendMessage = async () => {
    let info = {
        businessID: 'imgMsg',
        type: 'imgMsg',
        desc: '',
        ext: '<p>请确认您的信息是否正确</p>',
        imageUrl: ''
    };
    sendInfo.value.map(item => {
        if (item == 1) {
            info.ext += `<p>用户名称：${archiveInfo.value.auth_name}</p>`;
        }
        if (item == 2) {
            info.ext += `<p>联系电话：${archiveInfo.value.mobile}</p>`;
        }
        if (item == 3) {
            info.ext += `<p>联系地址：${archiveInfo.value.contact_address}</p>`;
        }
        if (item == 4) {
            info.imageUrl = archiveInfo.value.license;
        }
    })
    const payload = {
        data: JSON.stringify(info),
        description: '',
        extension: '',
    };
    const options = {
        to:
            currentConversation?.value?.groupProfile?.groupID
            || currentConversation?.value?.userProfile?.userID,
        conversationType: currentConversation?.value?.type,
        payload,
        needReadReceipt: isEnabledMessageReadReceiptGlobal(),
    };
    const offlinePushInfoCreateParams: IOfflinePushInfoCreateParams = {
        conversation: currentConversation.value,
        payload: options.payload,
        messageType: TUIChatEngine.TYPES.MSG_CUSTOM,
    };
    const sendMessageOptions: SendMessageOptions = {
        offlinePushInfo: OfflinePushInfoManager.create(offlinePushInfoCreateParams),
    };
    TUIChatService.sendCustomMessage(options as SendMessageParams, sendMessageOptions);
    dialogVisible.value = false;
};


const openSelectMsg = () => {
    showMsgList.value = true;
}

const delMsg = (e: number) => {
    mulitpleSelectStore.selectList.splice(e, 1);
}
</script>

<style lang="scss" scoped deep>
.wrap {
    padding: 20px 20px 10px;

    .title {
        font-size: 18px;
        font-weight: bold;
        color: #333333;
    }

    .content {
        padding: 20px 0 0;
        height: calc(100vh - 120px);
        overflow-y: auto;

        .tit {
            font-size: 16px;
            margin-bottom: 20px;
        }
    }

    .footer {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 49px;
        border-top: 1px solid #f4f5f9;
    }
}
</style>